<script setup>
  import { ref, computed } from 'vue'
  import { onLoad } from '@dcloudio/uni-app'
  import { tasksDelayAPI } from '@/apis/task'

  const _id = ref('')
  const planDepartureTime = ref('')
  // 延迟提货时间
  const delayTime = ref('')
  // 延迟原因
  const delayReason = ref('')

  const delayTimeValid = computed(() => {
    // 延迟时间不超过2小时
    const start = new Date(planDepartureTime.value)
    const end = new Date(delayTime.value)
    // 时间差区间在 0 ~ 7200 * 1000 毫秒
    return end - start > 0 && end - start <= 7200 * 1000
  })

  const wordsCount = computed(() => {
    return delayReason.value.length
  })

  // 验证延迟原因
  const delayReasonValid = computed(() => {
    return wordsCount.value <= 50 && wordsCount.value > 0
  })
  //用计算属性和按钮disabled绑定
  const enableSubmit = computed(() => {
    return !delayReasonValid.value || !delayTimeValid.value
  })

  onLoad((options) => {
    console.log(options)
    _id.value = options.id
    planDepartureTime.value = options.planDepartureTime
  })
  //日期事件
  function onPickerChange(e) {
    // console.log(e.detail.value)
    //和对象解构一样
    const [date] = planDepartureTime.value.split(' ')
    delayTime.value = `${date} ${e.detail.value}`
  }

  async function onSubmit() {
    const res = await tasksDelayAPI({
      delayReason: delayReason.value,
      delayTime: delayTime.value,
      id: _id.value,
    })
    // 跳转到任务列表
    uni.reLaunch({ url: '/pages/task/index' })
  }
</script>

<template>
  <view class="page-container">
    <uni-list :border="false">
      <uni-list-item
        title="原定时间"
        showArrow
        :rightText="planDepartureTime"
      />
      <uni-list-item title="延迟时间" showArrow>
        <template v-slot:footer>
          <picker @change="onPickerChange" class="time-picker" mode="time">
            <text v-if="!delayTime">不可超过2个小时</text>
            <text v-else :class="{ error: !delayTimeValid }"
              >{{ delayTime }}:00</text
            >
          </picker>
        </template>
      </uni-list-item>
      <uni-list-item direction="column">
        <template v-slot:body>
          <view class="textarea-wrapper">
            <textarea
              class="textarea"
              placeholder-style="color: #818181"
              placeholder="请输入延迟提货原因"
              v-model="delayReason"
              maxlength="50"
            ></textarea>
            <text class="words-count">{{ wordsCount }}/50</text>
          </view>
        </template>
      </uni-list-item>
      <uni-list-item :border="false">
        <template v-slot:body>
          <button :disabled="enableSubmit" class="button" @click="onSubmit">
            提交
          </button>
        </template>
      </uni-list-item>
    </uni-list>
  </view>
</template>

<style lang="scss" scoped>
  @import './index.scss';
</style>
